const app = getApp()
const WXAPI = require("../../../../api/newApi")
import {
  base64src
} from '../../../../utils/base64ImgUrl'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareImg: '',
    id: '', //预付卡id
    info: {},
    imgHttp: app.globalData.imgHttp, //图片前缀
    shopIcon: '', //店铺头像
    qrCode: '', //二维码
    base64img: '', //base64图片
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      statusHeight: app.gettop.height,
      status: app.gettop.status,
      navHeight: app.gettop.navHeight,
      mobbleBottom: app.mobile.mobbleBottom
    })
    this.data.id = options.id
    this.getDetail()
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.canvasdraw()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '可信安全的钱包，点击立即拥有',
      path: `/pages/assets/assets`,
      imageUrl: '../img/onShare.png',
    }
  },
  getDetail() {
    wx.showLoading({
      title: '加载中',
    })
    var id = this.data.id
    var url = `/app/v2/customer/asset/card/share/${id}`
    WXAPI.honerShare(url, '', res => {
      this.data.info = res.result
      this.setData({
        info: res.result
      })
      base64src(res.result.qrCode, res => {
        console.log(res) // 返回图片地址，直接赋值到image标签即可
        this.data.qrCode = res
      });
      this.getimg()
      setTimeout(() => {
        this.canvasdraw()
      }, 500)
      wx.hideLoading()
    })
  },
  getimg() { //生成本地头像路径
    var that = this
    wx.getImageInfo({
      //保存网络图片
      src: that.data.imgHttp + that.data.info.shopIcon,
      success: function (res) {
        console.log('本地头像', res.path)
        that.data.shopIcon = res.path
      }
    })
  },
  back() {
    wx.navigateBack({
      delta: 0,
    })
  },
  canvasdraw: function (canvas) {
    var that = this;
    console.log('that.data.qrCode', that.data.qrCode)
    const ctx = wx.createCanvasContext('canvas')
    ctx.save()
    var path = "../img/share_bj.png";
    ctx.drawImage(path, 0, 0, 750, 1448);
    ctx.restore()
    ctx.save()
    var path2 = that.data.shopIcon;
    ctx.arc(120, 120, 40, 0, 2 * Math.PI)
    ctx.clip()
    ctx.drawImage(path2, 60, 60, 120, 120)
    ctx.restore()
    ctx.save()
    var str = this.data.info.shopName
    const fontWidth= ctx.measureText(str).width;//获取文本宽度
    // ctx.font = 'normal bold 20px sans-serif';
    // ctx.setTextAlign('center'); // 文字居中
    // ctx.fillRect(0, 0, 200, 200);
    ctx.setFillStyle("#fff");
    ctx.setFontSize(44)
    ctx.fillText(str, 190, 130)
    // ctx.fillText(str, 360, 0 + fontWidth);
    ctx.restore()
    ctx.save()
    var str = '我们热烈祝贺，'
    // ctx.font = 'normal bold 20px sans-serif';
    ctx.setTextAlign('center'); // 文字居中
    ctx.setFillStyle("#000");
    ctx.setFontSize(44)
    ctx.fillText(str, 300, 480)
    // ctx.draw()
    var str2 = this.data.info.buyerName
    ctx.setFontSize(40)
    ctx.setFillStyle("#F5193C");
    ctx.setTextAlign('center');
    ctx.fillText(str2, 210, 555)
    ctx.restore()
    ctx.save()
    var str2 = '成为本店股东。'
    ctx.setFontSize(40)
    ctx.setFillStyle("#000");
    ctx.setTextAlign('center');
    ctx.fillText(str2, 430, 555)
    ctx.restore()
    ctx.save()
    var str = '享受本店股东分红、分佣。'
    ctx.setFontSize(32)
    ctx.setFillStyle("#444444");
    ctx.setTextAlign('center');
    ctx.fillText(str, 340, 655)
    ctx.restore()
    ctx.save()
    var str = '发证时间：' + this.data.info.time
    ctx.setFontSize(24)
    ctx.setFillStyle("#999999");
    ctx.setTextAlign('center');
    ctx.fillText(str, 268, 755)
    ctx.restore()
    ctx.save()
    var str = '发证企业：'
    ctx.setFontSize(24)
    ctx.setFillStyle("#999999");
    ctx.setTextAlign('center');
    ctx.fillText(str, 204, 800)
    ctx.restore()
    ctx.save()
    var str = this.data.info.merchantName
    // ctx.setFontSize(24)
    // ctx.setFillStyle("#999999");
    ctx.setTextAlign('center');
    // ctx.fillText(str, 375, 800)
    ctx.restore()
    ctx.save()
    var chr = str.split(""); //这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    ctx.setFontSize(24)
    ctx.setFillStyle("#999999")
    for (var a = 0; a < chr.length; a++) {
      if (ctx.measureText(temp).width < 250) {
        temp += chr[a];
      } else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);

    //如果数组长度大于2 则截取前两个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (ctx.measureText(test).width < 220) {
          test += rowPart[a];
        } else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..." //这里只显示两行，超出的用...表示
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      ctx.fillText(row[b], 268, 800 + b * 30, 500);
    }
    // var path6 = canvas;
    // ctx.drawImage(path2, 0, 0, 70, 70);
    ctx.drawImage(that.data.qrCode, 180, 916, 120, 120)
    ctx.restore()
    ctx.draw()
    setTimeout(() => {
      this.daochu()
    }, 500)

  },
  daochu() {
    console.log(1111)
    var _this = this
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 750,
      height: 1440,
      destWidth: 750,
      destHeight: 1440,
      fileType: 'jpg', //图片的质量，目前仅对 jpg 有效。取值范围为 (0, 1]，不在范围内时当作 1.0 处理。
      quality: 1,
      canvasId: 'canvas',
      success(res) {
        console.log(222)
        console.log(res.tempFilePath)
        _this.data.shareImg = res.tempFilePath
        _this.setData({
          img: res.tempFilePath
        })
        console.log('img', _this.data.img)
      }
    })
  },
  //点击保存图片
  save() {
    let that = this
    //若二维码未加载完毕，加个动画提高用户体验
    wx.showToast({
      icon: 'loading',
      title: '正在保存图片',
      duration: 1000
    })
    //判断用户是否授权"保存到相册"
    wx.getSetting({
      success(res) {
        //没有权限，发起授权
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() { //用户允许授权，保存图片到相册
              that.savePhoto();
            },
            fail() { //用户点击拒绝授权，跳转到设置页，引导用户授权
              wx.openSetting({
                success() {
                  wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success() {
                      that.savePhoto();
                    }
                  })
                }
              })
            }
          })
        } else { //用户已授权，保存到相册
          that.savePhoto()
        }
      }
    })
  },
  //保存图片到相册，提示保存成功
  savePhoto() {
    let that = this
    let img = that.data.shareImg
    console.log(that.data.shareImg)
    if (that.data.shareImg == '') {
      wx.showToast({
        title: '图片加载中，请稍后',
        icon: 'none'
      })
      return
    }
    // console.log(this.data.Imgurl)
    var save = wx.getFileSystemManager();
    var number = Math.random();
    wx.saveImageToPhotosAlbum({
      filePath: img,
      success: function (res) {
        wx.showToast({
          title: '保存成功',
        })
      },
      fail: function (err) {
        console.log(err)
      }
    })
    // save.writeFile({
    //   filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
    //   data: img.slice(22),
    //   encoding: 'base64',
    //   success: res => {
    //     wx.saveImageToPhotosAlbum({
    //       filePath: img,
    //       success: function (res) {
    //         wx.showToast({
    //           title: '保存成功',
    //         })
    //       },
    //       fail: function (err) {
    //         console.log(err)
    //       }
    //     })
    //     console.log(res)
    //   }, fail: err => {
    //     wx.showToast({
    //       title: '保存失败',
    //       icon:'none'
    //     })
    //     console.log(err)
    //   }
    // })
  },
})